import 'dart:io';
import 'package:http_server/http_server.dart' as http_server;
import 'package:path/path.dart';
import '../utils/StringCreate.dart';
import '../config/Config.dart' as cnf;

class FileManager {
  static String myPath = dirname(Platform.script.toFilePath());

  static String get serverPath {
    var port = cnf.env == cnf.PROD ? cnf.PROD_PORT : cnf.DEBUG_PORT;
    return 'http://' + cnf.IP + ':' + port.toString();
  }

  static void sendFile(String file_path, HttpRequest req) async {
    var staticFiles = http_server.VirtualDirectory('.');
    staticFiles.serveFile(File(myPath + file_path), req); //win系统使用该代码
  }

  static Future<String> saveFile(String filename, var content,
      {String path = r'/../image/'}) async {
    try {
      var name = DateTime.now().millisecondsSinceEpoch.toString();
      name = name +
          createRandomVerifyNum(20 - name.length) +
          filename.substring(filename.lastIndexOf('.'), filename.length);
      var finalPath = myPath + path + name;
      var file = File(finalPath);
      await file.writeAsBytes(content);
      return name;
    } catch (e) {
      return '存储出错';
    }
  }
}
